<?php

namespace App\Store\Models\Goods;

use App\Common\Services\Common;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\Supply;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class GoodsReturn extends Model
{
    protected $table = 'site_goods_return';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    /**
     *获取列表
     */
    public static function getList(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $query = self::with(['storeinfo', 'infolist' => function ($query) {
            $query->where('is_del', 1);
        }]);

        //起始门店
        $store_id = $request['store_id'] ?? 0;
        if ($store_id > 0) {
            $query->where('store_id', $store_id);
        }

        $store_ids=$request['store_ids'] ?? [];
        if (!empty($store_ids)) {
            $store_ids =is_array($store_ids)?$store_ids:[$store_ids];
            $query->whereIn('store_id', $store_ids);
        }

        //订单状态
        $audit_status = $request['audit_status'] ?? 0;
        if ($audit_status > 0) {
            $query->where('audit_status', $audit_status);
        }else{
            $not_audit=intval($request->not_audit);

            if($not_audit>=1){
                $query->whereIn('audit_status',[1,2]);
            }
        }

        //订单号
        $order_sncode = $request['order_sncode'] ?? '';
        if ($order_sncode != '') {
            $query->where('order_sncode', 'like', $order_sncode);
        }

        //时间筛选
        $start_time = (!is_numeric($request->start_time) && strtotime($request->start_time) > 0) ? strtotime($request->start_time) : intval($request->start_time);
        $end_time = (!is_numeric($request->end_time) && strtotime($request->end_time) > 0) ? strtotime($request->end_time) : intval($request->end_time);
        if ($start_time > 0 && $end_time > $start_time) {
            $query->where('create_at', '>=', $start_time)->where('create_at', '<=', $end_time);
        }

        $query->where('is_del', 1)->where('cp_id', $cp_id)->orderBy('create_at', 'desc');

        $isgetall = $request['isgetall'] ?? 0;
        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return Common::paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }

    /**
     * 明细表
     */
    public function infolist()
    {
        return $this->hasMany(GoodsReturnInfolist::class, 'p_id', 'id');
    }

    /**
     * 店铺
     */
    public function storeinfo()
    {
        return $this->hasOne(SiteStore::class, 'id', 'store_id')->select('id', 'store_name');
    }
}
